package com.dcbeida.callback;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;

import com.dcbeida.utils.GetApi;
import com.dcbeida.utils.MD5Util;
import dc.medicine.com.okhttplib.model.HttpParams;
import dc.medicine.com.okhttplib.request.BaseRequest;

/**
 * Created by hp on 2016/7/18.
 */
public abstract class EncryptCallback<T> extends CommonCallback<T>  {




    @Override
    public void onBefore(BaseRequest request) {
        super.onBefore(request);
        sign(request.getParams());

    }

    /**
     * 针对URL进行签名，关于这几个参数的作用，详细请看
     * http://www.cnblogs.com/bestzrz/archive/2011/09/03/2164620.html
     */
    private void sign(HttpParams params) {
        params.appsParmas.put("timespan",System.currentTimeMillis() + "");
        params.appsParmas.put("appid",GetApi.APPID);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : getSortedMapByKey(params.appsParmas).entrySet()) {
            sb.append(entry.getValue());
        }
        sb.append(GetApi.KEY);
        String hash = MD5Util.MD5(sb.toString()).toLowerCase();
        params.appsParmas.put("hash", hash);


    }

    /** 按照key的自然顺序进行排序，并返回 */
    private Map<String, String> getSortedMapByKey(ConcurrentHashMap<String, String> map) {

        Comparator<String> comparator = new Comparator<String>() {
            @Override
            public int compare(String lhs, String rhs) {
                return lhs.compareTo(rhs);
            }
        };

        TreeMap<String, String> treeMap = new TreeMap<>(comparator);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            treeMap.put(entry.getKey(), entry.getValue());
        }
        return  treeMap;

    }
}
